package com.sfx.concurrent.demo.concurrent.AtomicTest.Atomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-18
 * Time: 18:38
 */
public class TestDemo2 {

    /**
     * updateAndGet/getAndUpdate 可以实现加减乘除->使用lambda表达式
     * @param args
     */
    public static void main(String[] args) {
        AtomicInteger i = new AtomicInteger(1);
        //          原始值     要设置的值
        updateAndGet(i,val->val*10);
        System.out.println(i.get());
    }

    public static void updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
        while(true) {
            int prev = i.get();
            //要修改的值
            int next = operator.applyAsInt(prev);
            if(i.compareAndSet(prev,next)) {
                break;
            }
        }
    }

}
